import React, {FC, useCallback, useEffect, useMemo, useState} from "react";
import {useParams} from "react-router";
import {useTranslation} from "react-i18next";
import "../css/TabContent.less";
import {importComponent, strToObject} from "../../utils";
import {loadMenu, openEditUrl} from "../../services/MenuService.tsx";
import {GlobalErr} from "../../global/GlobalErr.tsx";


interface TabContentProps {
    menuId?: string
    key?: string
}

const TabContent: FC<TabContentProps> = (props) => {

    const {t} = useTranslation();

    const urlParams = useParams();

    const [component, setComponent] = useState<object>({});

    const initContent = useCallback(async (params = {}) => {
        const {menuId, initParams} = params;
        if (!menuId) {
            return false;
        }
        const res = await loadMenu({id: menuId});
        let Com, comProps = strToObject(res.operate);
        if (!res.subassembly) {
            Com = GlobalErr;
            comProps.errContent = (<div>
                <span className={"sf_core_link"} onClick={() => {
                    openEditUrl(menuId)
                }}>{menuId}</span>
                <span>{t("unComPath")}</span>
            </div>);
        } else {
            Com = await importComponent(res.subassembly);
            Com = Com ? Com : GlobalErr;
            !Com && (comProps.errContent = t("errorComPath"));
        }
        if (comProps.tableApi && initParams) {
            comProps.tableApi.params || (comProps.tableApi.params = {});
            comProps.tableApi.params = {...comProps.tableApi.params, ...initParams}
        }
        setComponent({
            dom: Com,
            menuId: res.id,
            params: comProps
        })
    }, [urlParams]);

    useEffect(() => {
        initContent(props.menuId ? props : urlParams);
    }, []);

    const renderTabContent = useMemo(() => {
        if (!Object.keys(component).length) {
            return null
        }
        const {dom, params = {}, menuId} = component;
        const Com = dom;
        return (
            <Com key={props.key} menuId={menuId} {...params} />
        )
    }, [component, props.key]);

    return (<div className={"sf_core_main_layout_content_main_content"}>
        {renderTabContent}
    </div>)
};

export default TabContent;